
using System;
using System.Collections.Generic;
using System.Text;

namespace SharpSoft.Html
{
    using AngleSharp.Dom;
    using System.Threading.Tasks;

    /// <summary>
    /// 抓取页面
    /// </summary>
    public class HtmlFetchingPage
    {
        public string name { get; set; }
        /// <summary>
        /// 当前页面的固定url（如果是固定页面）
        /// </summary>
        public string url { get; set; }
        /// <summary>
        /// 移除节点
        /// </summary>
        public string[] delnode { get; set; }

        public HtmlFetchingProperty[] properties { get; set; }
        /// <summary>
        /// 一个属性路径，指向下一页的url
        /// </summary>
        public PropertyPath nextpage { get; set; }
        /// <summary>
        /// 分页，这个值指向一个属性名称，将属性值作为新页面的url
        /// </summary>
        public string paging { get; set; }
        /// <summary>
        /// 获取所有属性的值
        /// </summary>
        /// <param name="doc"></param>
        /// <returns></returns>
        public HtmlFetchingPropertyValue[] GetPropertyValues(IDocument doc)
        {
            if (properties == null)
            {
                return null;
            }
            HtmlFetchingPropertyValue[] vl = new HtmlFetchingPropertyValue[properties.Length];
            properties.Each((i, item) =>
            {
                vl[i] = item.GetValue(doc);
            });
            return vl;
        }
        /// <summary>
        /// 获取分页指向的下一页网址
        /// </summary>
        /// <param name="doc"></param>
        /// <returns></returns>
        public string GetPagingNextUrl(IDocument doc)
        {
            if (string.IsNullOrEmpty(paging))
            {
                return null;
            }
            var pvs = GetPropertyValues(doc);
            var pv = pvs.GetPropertyValue(paging);
            if (pv == null)
            {
                return null;
            }
            if (string.IsNullOrEmpty(pv.value as string))
            {
                return null;
            }
            return FetchingExtensions.CombineUrl(doc.BaseUri, pv.value.ToString());
        }
        /// <summary>
        /// 获取当前页面指定的实例的文档
        /// </summary>
        /// <param name="address"></param>
        /// <returns></returns>
        public async Task<IDocument> ExecuteAsync(string address)
        {
            var doc = await Loader.loadAsync(address);
            if (delnode != null)
            {//移除多余节点
                foreach (var item in delnode)
                {
                    var eles = doc.q(item);
                    foreach (var ele in eles)
                    {
                        ele.Remove();
                    }
                }
            }
            return doc;
        }
    }
}
